import { Input, Typography } from '@arco-design/web-react';
import React, { useEffect, useState } from "react";
import { log, info, warn, error } from "@/util/tio"

export default function UseEffectDemo() {
    const [message, setMessage] = useState("hello, t-io");
    const [logs, setLogs] = useState([]);

    // https://zh-hans.reactjs.org/docs/hooks-effect.html
    const mylog = (str) => {
        log(str);

        // 注意数组及对象的更新，一定要用函数
        setLogs(oldArray => [...oldArray, str]);  //正确的示范

        // 下面两行是错误的示范，因为下面的写法，logs作为一个整体，并没有被“改变”
        // logs.push(str)
        // setLogs(logs);
    }

    useEffect(() => {
        const id = setInterval(() => {
            mylog('timer - ' + id);
        }, 6000);
        mylog('start - ' + id);
        return () => {
            // 每次修改message就会执行return里的语句
            mylog('end - ' + id);
            clearInterval(id);
        };
    }, [message]);

    /**
     * 第二个参数是空数组时，则是组件加载和卸载时执行
     */
    useEffect(() => {
        mylog('组件加载了... ...');
        return () => {
            mylog('组件卸载了... ...');
        };
    }, []);


    return (
        <>
            <Input
                style={{ width: 350, margin: "10px" }}
                allowClear
                placeholder='Please Enter something'
                value={message}
                onChange={(v, e) => setMessage(e.target.value)}
            />

            <div className="bg-gray-700 text-green-400 text-size-0.8rem p-2 m-3 divide-y divide-solid divide-green-500 ">
                message: "{message}"
                {
                    logs.map((item, i) => {
                        return <div key={i} className='py-4px'>{item}</div>
                    })
                }
            </div>
        </>
    );
}
